import { useState, useEffect, useRef } from 'react'
import { Form, Radio, Checkbox, Space, Button, Input, MessagePlugin } from 'tdesign-react'
import { apis, ApiRequest } from '@/service'

import '../index.less'

const { FormItem } = Form

const {
  practiceService: {
    insertAnswer,
    getAnswer
  }
} = apis

const RenderQuestionnaire = (props: any) => {

  const {
    title = '',
    questionList = [],
    currentUser = {},
  } = props

  const [answerData, setAnswerData] = useState<any>({})

  const answerRef = useRef<any>(null)

  useEffect(() => {
    currentUser?.userId && title && getAnswerFunction()
  }, [currentUser, title])

  useEffect(() => {
    answerRef.current?.setFieldsValue(answerData)
  }, [answerData])

  /**
  * 提交问卷答案
  * @param params
  */
 const insertAnswerFunction = (params: any) => {
   // 参数加上用户的 id
   params = {
     title: title,
     userId: currentUser?.userId,
     id: answerData?.id || '',
     ...params
   }
   ApiRequest({ api: insertAnswer, params }).then((res: any) => {
     const { code = -1, data = [], note = '' } = res
     if (code > 0) {
       // setTodoList(data)
       MessagePlugin.success({
         content: note,
         placement: 'top-right',
         duration: 2000
       })
     }
   })
 }

 /**
  * 获取问卷答案
  * @param event
  */
 const getAnswerFunction = () => {
  const params =  {
    userId: currentUser?.userId,
    title,
  }
  ApiRequest({ api: getAnswer, params }).then((res: any) => {
    const { code = -1, data = [], note = '' } = res
    if (code > 0) {
      if (data.length) {
        let { userId, title, ..._answerData } = data[0]
        setAnswerData(_answerData)
        note && MessagePlugin.success({
          content: note,
          placement: 'top-right',
          duration: 2000
        })
      } else {
        // 应该是 {} 不包含字段名称，所以这个方法不知道要怎么修改这些值，首先使用 getFieldsValue 方法获取所有表单的名称和值
        // 然后遍历这个对象，让对象的值都为空，再把这个空对象赋值给 answerData
        let prevAnswerData = answerRef.current?.getFieldsValue(true)
        for (let key in prevAnswerData) {
          prevAnswerData[key] = ''
        }
        setAnswerData(prevAnswerData) // answer data 应该是个对象才对
      }

    }
  })
 }

  const onSubmit = (event: any) => {
    insertAnswerFunction(event.fields)
  }

  const onReset = () => {
    console.log('reset')
  }

  return <Form
    ref={answerRef}
    className="question-form"
    onSubmit={onSubmit}
    onReset={onReset}
    labelWidth={200}
    labelAlign={'top'}
    resetType='initial'
  >
    {
      questionList.map((question: any, index: number) => {
        if (question.type === 'radio') {
          // return <FormItem label={`选项${translateDigitToChinese(index)}：${question.title}`} name={question.title} key={index}>
          return <FormItem label={`第 ${index + 1} 题：${question.title}`} name={question.title} key={index}>
            <Radio.Group>
              {
                question.optionList.map((item: any) => {
                  return <Radio value={item.value} key={item.value}>{item.label}</Radio>
                })
              }
            </Radio.Group>
          </FormItem>
        }
        else if (question.type === 'checkbox') {
          return <FormItem label={`第 ${index + 1} 题：${question.title}`} name={question.title} key={index}>
            <Checkbox.Group>
              {
                question.optionList.map((item: any) => {
                  return <Checkbox value={item.value} key={item.value}>{item.label}</Checkbox>
                })
              }
            </Checkbox.Group>
          </FormItem>
        }
        else if (question.type === 'input') {
          return <FormItem label={`第 ${index + 1} 题：${question.title}`} name={question.title} key={index}>
            <Input />
          </FormItem>
        }
        // return <FormItem label={question.title} name={question.title}>
        //   {(() => {
        //     switch (question.type) {
        //       case 'radio':
        //         return <Radio.Group>
        //           {
        //             question.radioList.map((item: any) => {
        //               return <Radio value={item.value} key={item.value}>{item.label}</Radio>
        //             })
        //           }
        //         </Radio.Group>
        //       case 'checkbox':
        //         return <Checkbox.Group>
        //           {
        //             question.checkList.map((item: any) => {
        //               return <Checkbox value={item.value} key={item.value}>{item.label}</Checkbox>
        //             })
        //           }
        //         </Checkbox.Group>
        //       case 'input':
        //         return <Input />
        //       default:
        //         return <Input />
        //     }
        //   })}
        // </FormItem>
      })
    }
    <FormItem style={{ marginLeft: 200 }}>
      <Space>
        <Button type="submit" theme="primary">
          提交
        </Button>
        <Button type="reset" theme="default">
          重置
        </Button>
      </Space>
    </FormItem>

  </Form>
}

export default RenderQuestionnaire



/* <FormItem label="你的工作时间是多少？" name="q1">
      <Radio.Group>
        <Radio value="1">8h</Radio>
        <Radio value="2">9h</Radio>
        <Radio value="3">10h</Radio>
        <Radio value="4">12h及以上</Radio>
      </Radio.Group>
    </FormItem>
    <FormItem label="你的性别是什么？" name="q2">
      <Radio.Group>
        <Radio value="1">男</Radio>
        <Radio value="0">女</Radio>
      </Radio.Group>
    </FormItem>
    <FormItem label="你有多少个对象？" name="q3">
      <Radio.Group>
        <Radio value="1">1个</Radio>
        <Radio value="2">2个</Radio>
        <Radio value="3">3个</Radio>
        <Radio value="4">4个及以上</Radio>
      </Radio.Group>
    </FormItem>
    <FormItem label="你是前端还是后端？" name="q4">
      <Radio.Group>
        <Radio value="1">前端</Radio>
        <Radio value="2">后端</Radio>
        <Radio value="3">全栈</Radio>
      </Radio.Group>
    </FormItem>
    <FormItem label="你最喜欢的编程语言是什么？" name="q5">
      <Checkbox.Group>
        <Checkbox value="java">Java</Checkbox>
        <Checkbox value="C++">C++</Checkbox>
        <Checkbox value="Python">Python</Checkbox>
        <Checkbox value="JavaScript">JavaScript</Checkbox>
        <Checkbox value="C#">C#</Checkbox>
        <Checkbox value="PHP">PHP</Checkbox>
        <Checkbox value="Ruby">Ruby</Checkbox>
        <Checkbox value="Swift">Swift</Checkbox>
        <Checkbox value="Kotlin">Kotlin</Checkbox>
        <Checkbox value="Rust">Rust</Checkbox>
      </Checkbox.Group>
    </FormItem>
    <FormItem label="你最喜欢的游戏是什么？" name="q6">
      <Checkbox.Group>
        <Checkbox value="hok">王者荣耀</Checkbox>
        <Checkbox value="cf">穿越火线</Checkbox>
        <Checkbox value="fc">QQ飞车</Checkbox>
        <Checkbox value="lol">英雄联盟</Checkbox>
        <Checkbox value="gfp">和平精英</Checkbox>
        <Checkbox value="yys">阴阳师</Checkbox>
        <Checkbox value="wow">魔兽世界</Checkbox>
      </Checkbox.Group>
    </FormItem>
    <FormItem label="你最喜欢的运动是什么？" name="q7">
      <Input />
    </FormItem>
    <FormItem label="你的工作地点是哪里？" name="q8">
      <Input />
    </FormItem>
    <FormItem style={{ marginLeft: 200 }}>
    <Space>
      <Button type="submit" theme="primary">
        提交
      </Button>
      <Button type="reset" theme="default">
        重置
      </Button>
    </Space>
    </FormItem> */
